package com.example.my2048.game.view;

import static java.lang.Math.max;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;

import com.example.my2048.game.model.Board;

@SuppressLint("ViewConstructor")
public class BoardView extends View {
    private Board board;
    private Paint paint;

    public BoardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.paint = new Paint();
        this.paint.setAntiAlias(true);
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);
        if (this.board == null) {
            return;
        }
        Integer[][] boardData = this.board.getTiles();
        int tileWidth = getWidth() / this.board.getColNum();
        int tileHeight = getWidth() / this.board.getRowNum();
        int deltaHeight = (getHeight() - getWidth()) / 2;
        for (int i = 0; i < this.board.getRowNum(); i++) {
            for (int j = 0; j < this.board.getColNum(); j++) {
                int value = boardData[i][j];
                int color = getColorForValue(value);
                this.paint.setColor(color);
                float l = j * tileWidth;
                float t = i * tileHeight + deltaHeight;
                float r = l + tileWidth;
                float d = t + tileHeight;
                canvas.drawRect(l, t, r, d, this.paint);
                if (value != 0) {
                    this.paint.setColor(Color.BLACK);
                    this.paint.setTextSize((float) max(tileHeight, tileWidth) / 2);
                    this.paint.setTextAlign(Paint.Align.CENTER);
                    canvas.drawText(String.valueOf(value), (j + 0.5f) * tileWidth, (i + 0.5f) * tileHeight + deltaHeight, this.paint);
                }
            }
        }
    }

    public int getColorForValue(int value) {
        if (value == 0) return Color.argb(255, 255, 255, 255);
        return Color.argb(255, value * 4, value * 16, value * 4);
    }

    public void setBoard(Board board) {
        this.board = board;
        invalidate();
    }

}
